from google.appengine.ext.webapp import template
from google.appengine.api import users

def render(path, template_values, title='Untitled', css=[], modules={}):
    '''Render all page.'''

    buffer  = render_header(title, css, modules)

    if (path != None):
        buffer += template.render(path, template_values) 

    buffer += render_footer()

    return buffer

def render_header(title, css=[], modules={}):
    '''Render only header'''

    header = prepare_header_values(title, css, modules)
    return template.render('templates/header.html', header)

def render_footer():
    '''Render only footer.'''

    footer = prepare_footer_values()
    return template.render('templates/footer.html', footer)
     
    

def prepare_header_values(title='Untitled', css=[], modules={}):
    user = users.get_current_user()
    values = {
        'Page': Page(title),
        'cssfiles': css,
    }
    if len(modules) > 0:
        modules = map(lambda module: [module, modules[module]['name']], modules)
        values['modules'] = modules

    if user:
        values['nickname'] = user.nickname()
        values['logout_url'] = users.create_logout_url('/')

    return values

def prepare_footer_values():
    return []

class Page(object):
    '''Page object'''

    def __init__(self, title='Untitled'):
        self.title = title


